let _Vue = null;
export default class VueRouter {
    constructor(options) {
        this.options = options;
        this.routeMap = {};
        this.data = _Vue.observable({
            current: "/"
        });
    }
    static install(vue) {
        if (this.install.installed) {
            return;
        }
        VueRouter.install.installed = true;
        _Vue = vue;
        _Vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router;
                    this.$options.router.init();
                }
            }
        });
    }
    init() {
        this.createRouteMap();
        this.initComponents(_Vue);
        this.initEvent();
    }
    createRouteMap() {
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component;
        });
    }
    initComponents(Vue) {
        const _this = this;
        Vue.component("router-view", {
            render(h) {
                const component = _this.routeMap[_this.data.current];
                return h(component);
            }
        });
        Vue.component("router-link", {
            props: {
                to: String
            },
            render(h) {
                return h(
                    "a",
                    {
                        attrs: {
                            href: "#" + this.to
                        }
                    },
                    [this.$slots.default]
                );
            }
        });
    }
    initEvent() {
        window.addEventListener("hashchange", () => {
            this.data.current = location.hash.replace("#", "");
        });
        window.addEventListener("load", () => {
            const hash = location.hash;
            if (!hash || hash.startsWith("#")) {
                location.hash = "#/";
            }
            this.data.current = location.hash.replace("#", "");
        });
    }
}
